package com.example.api.service.impl;

import com.example.api.dto.LoginDTO;
import com.example.api.entity.User;
import com.example.api.mapper.UserMapper;
import com.example.api.service.AuthService;
import com.example.api.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public AuthServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        logger.debug("开始处理登录请求，用户名: {}", loginDTO.getUsername());
        
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            logger.warn("登录失败：用户不存在，用户名: {}", loginDTO.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            logger.warn("登录失败：密码错误，用户名: {}", loginDTO.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(user.getUsername());
        logger.debug("生成token成功，用户名: {}", loginDTO.getUsername());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        
        // 创建不包含密码的用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("email", user.getEmail());
        userInfo.put("role", user.getRole());
        
        result.put("user", userInfo);
        logger.debug("登录成功，返回数据: {}", result);
        
        return result;
    }
} 